package com.slipper.codeless.token;

import com.slipper.system.codeless.bo.InterfaceTokenBO;
import com.slipper.util.DateUtil;
import com.slipper.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class TokenManager implements ApplicationRunner {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final ConcurrentHashMap<String, InterfaceTokenBO> tokenCache = new ConcurrentHashMap<>();

    @Override
    public void run(ApplicationArguments args) {
        this.tokenMonitor();
    }

    public InterfaceTokenBO createToken(int time) {
        InterfaceTokenBO token = new InterfaceTokenBO();
        token.setToken(UUID.getUUID());
        token.setTokenTime(time);
        token.setCreateTime(System.currentTimeMillis());
        tokenCache.put(token.getToken(), token);
        return token;
    }

    public boolean validateToken(String token) {
        InterfaceTokenBO interfaceToken = tokenCache.get(token);
        if (interfaceToken == null) return false;

        if (DateUtil.secondDiff(interfaceToken.getCreateTime(), System.currentTimeMillis())
                <= interfaceToken.getTokenTime()) {
            return true;
        } else {
            tokenCache.remove(token);
            return false;
        }
    }

    public void tokenMonitor() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                tokenCache.forEach((key, value) -> {
                    if (DateUtil.secondDiff(value.getCreateTime(), System.currentTimeMillis()) > value.getTokenTime()) {
                        logger.info("清理无效的接口token: {}", key);
                        tokenCache.remove(key);
                    }
                });
            }
        }, 0, 30 * 60 * 1000L);
        logger.info("接口监控已启动...");
    }
}
